<template>
  <!-- Instructions Stage -->
  <div v-if="stage === 'instructions'" class="max-w-2xl mx-auto">
    <transition name="fade" appear>
      <Card class="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-lg">
        <CardHeader class="text-center pb-8">
          <div
            class="w-16 h-16 bg-gradient-to-br from-yellow-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Lightbulb class="w-8 h-8 text-white" />
          </div>
          <CardTitle class="text-2xl text-slate-800">{{
            t("criticalThinkingTest.title")
          }}</CardTitle>
          <p class="text-slate-600 mt-2">
            {{ t("criticalThinkingTest.description") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div
            class="bg-gradient-to-r from-yellow-50 to-orange-50 rounded-xl p-6 border border-yellow-100"
          >
            <h3
              class="font-semibold text-yellow-900 mb-4 flex items-center gap-2"
            >
              <Star class="w-5 h-5" />
              {{ t("criticalThinkingTest.institle") }}
            </h3>
            <div class="space-y-3 text-slate-700">
              <div class="flex gap-3">
                <span class="step-number">1</span>
                <p>{{ t("criticalThinkingTest.instruction1") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">2</span>
                <p>{{ t("criticalThinkingTest.instruction2") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">3</span>
                <p>{{ t("criticalThinkingTest.instruction3") }}</p>
              </div>
              <div class="flex gap-3">
                <span class="step-number">4</span>
                <p>{{ t("criticalThinkingTest.instruction4") }}</p>
              </div>
            </div>
          </div>
          <div class="grid md:grid-cols-2 gap-4">
            <div class="task-preview-box border-red-200 from-red-50 to-red-100">
              <h4
                class="font-semibold text-red-800 mb-2 flex items-center gap-2"
              >
                <AlertTriangle class="w-4 h-4" />
                {{ t("criticalThinkingTest.logicalFallaciesTitle") }}
              </h4>
              <p class="text-sm text-red-700">
                {{ t("criticalThinkingTest.logicalFallaciesDescription") }}
              </p>
            </div>
            <div
              class="task-preview-box border-blue-200 from-blue-50 to-blue-100"
            >
              <h4 class="font-semibold text-blue-800 mb-2">
                {{ t("criticalThinkingTest.argumentEvaluationTitle") }}
              </h4>
              <p class="text-sm text-blue-700">
                {{ t("criticalThinkingTest.argumentEvaluationDescription") }}
              </p>
            </div>
          </div>
          <div class="grid md:grid-cols-3 gap-4">
            <div
              class="info-box from-yellow-50 to-yellow-100 border-yellow-200"
            >
              <div class="info-box-title text-yellow-600">20+</div>
              <div class="info-box-body">
                {{ t("criticalThinkingTest.questionBankQuantity") }}
              </div>
            </div>
            <div
              class="info-box from-orange-50 to-orange-100 border-orange-200"
            >
              <div class="info-box-title text-orange-600">12</div>
              <div class="info-box-body">
                {{ t("criticalThinkingTest.randomQuestions") }}
              </div>
            </div>
            <div class="info-box from-yellow-50 to-orange-50 border-yellow-200">
              <div class="info-box-title text-slate-600">15</div>
              <div class="info-box-body">
                {{ t("criticalThinkingTest.timeLimitMinutes") }}
              </div>
            </div>
          </div>
          <Button
            @click="handleStartTest"
            class="w-full bg-gradient-to-r from-yellow-600 to-orange-500 hover:from-yellow-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
          >
            {{ t("criticalThinkingTest.startButton") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>

  <!-- Test Stage -->
  <div
    v-else-if="stage === 'test' && currentQuestionData"
    class="max-w-4xl mx-auto space-y-6"
  >
    <div class="flex flex-col sm:flex-row gap-4 items-center justify-between">
      <div class="flex items-center gap-4 flex-wrap">
        <Badge
          variant="outline"
          class="bg-yellow-100 text-yellow-700 border-yellow-300"
          >{{ t("criticalThinkingTest.questionLabel") }}
          {{ currentQuestion + 1 }} / {{ QUESTIONS_PER_TEST }}</Badge
        >
        <Badge variant="outline" :class="typeClass">{{ typeName }}</Badge>
        <Badge variant="outline" :class="difficultyClass">{{
          difficultyText
        }}</Badge>
        <div class="flex items-center gap-2 text-slate-600">
          <Trophy class="w-4 h-4" />
          <span class="font-semibold">{{ score }}</span>
        </div>
      </div>
      <div class="flex items-center gap-2">
        <Clock class="w-4 h-4 text-slate-500" />
        <span
          :class="[
            'font-mono text-lg font-bold',
            timeLeft <= 120 ? 'text-red-500' : 'text-slate-700',
          ]"
        >
          {{ Math.floor(timeLeft / 60) }}:{{
            (timeLeft % 60).toString().padStart(2, "0")
          }}
        </span>
      </div>
    </div>

    <Progress
      :model-value="(currentQuestion / QUESTIONS_PER_TEST) * 100"
      class="h-2"
    />

    <Card class="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200">
      <CardHeader>
        <div class="flex items-center gap-2 mb-2">
          <Badge variant="secondary" class="text-xs">{{
            currentQuestionData.context
          }}</Badge>
        </div>
        <CardTitle class="text-lg text-slate-800">{{
          t("criticalThinkingTest.scenarioAnalysisTitle")
        }}</CardTitle>
      </CardHeader>
      <CardContent
        ><p class="text-slate-700 leading-relaxed text-base italic">
          "{{ currentQuestionData.scenario }}"
        </p></CardContent
      >
    </Card>

    <Card class="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-lg">
      <CardHeader
        ><CardTitle class="text-xl text-slate-800">{{
          currentQuestionData.question
        }}</CardTitle></CardHeader
      >
      <CardContent class="space-y-4">
        <Button
          v-for="(option, index) in currentQuestionData.options"
          :key="index"
          variant="outline"
          @click="handleAnswer(index)"
          :disabled="showFeedback"
          class="w-full h-auto min-h-[3rem] text-left justify-start p-4 hover:bg-yellow-50 hover:border-yellow-300 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <div class="flex items-center gap-3">
            <span
              class="w-8 h-8 bg-yellow-100 text-yellow-700 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0"
              >{{ String.fromCharCode(65 + index) }}</span
            >
            <span class="text-slate-800">{{ option }}</span>
          </div>
        </Button>
      </CardContent>
    </Card>

    <transition name="slide-down">
      <div
        v-if="showFeedback"
        class="fixed top-20 left-1/2 transform -translate-x-1/2 z-50 max-w-2xl w-full mx-4"
      >
        <Card
          :class="[
            'border-0 shadow-xl',
            feedbackCorrect
              ? 'bg-green-500 text-white'
              : 'bg-red-500 text-white',
          ]"
        >
          <CardContent class="py-6 px-6">
            <div class="flex items-start justify-between gap-4">
              <div class="flex-1">
                <div class="font-semibold mb-3 text-lg">
                  {{
                    feedbackCorrect
                      ? t("criticalThinkingTest.correctFeedback")
                      : t("criticalThinkingTest.incorrectFeedback")
                  }}
                </div>
                <div class="text-sm opacity-95 leading-relaxed">
                  {{ feedbackExplanation }}
                </div>
              </div>
              <Button
                :variant="null"
                size="sm"
                @click="handleCloseFeedback"
                class="text-white bg-red-500 text-white hover:brightness-110 h-8 w-8 p-0 flex-shrink-0"
                ><X class="w-4 h-4"
              /></Button>
            </div>
            <div
              class="mt-4 pt-4 border-t border-white/20"
              style="background: transparent"
            >
              <Button
                @click="handleCloseFeedback"
                :variant="null"
                class="w-full bg-red-500 text-white hover:brightness-110 font-medium"
              >
                {{
                  currentQuestion < QUESTIONS_PER_TEST - 1
                    ? t("criticalThinkingTest.nextQuestionButton")
                    : t("criticalThinkingTest.viewResultsButton")
                }}
                →
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </transition>
  </div>

  <!-- Results Stage -->
  <div v-else-if="stage === 'results'" class="max-w-2xl mx-auto">
    <transition name="fade" appear>
      <Card class="bg-white/90 backdrop-blur-sm border-yellow-200 shadow-xl">
        <CardHeader class="text-center pb-6">
          <div
            class="w-20 h-20 bg-gradient-to-br from-yellow-600 to-orange-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
          >
            <Trophy class="w-10 h-10 text-white" />
          </div>
          <CardTitle class="text-3xl text-slate-800 mb-2">{{
            t("criticalThinkingTest.testCompleteTitle")
          }}</CardTitle>
          <div
            class="text-6xl font-bold bg-gradient-to-r from-yellow-600 to-orange-500 bg-clip-text text-transparent"
          >
            {{ results.accuracy }}
          </div>
          <p class="text-slate-600">
            {{ t("criticalThinkingTest.accuracyRate") }}
          </p>
        </CardHeader>
        <CardContent class="space-y-6">
          <div class="grid grid-cols-2 gap-4">
            <div
              class="info-box from-yellow-50 to-yellow-100 border-yellow-200"
            >
              <div class="info-box-title text-yellow-600">
                {{ score }}/{{ QUESTIONS_PER_TEST }}
              </div>
              <div class="info-box-body">
                {{ t("criticalThinkingTest.correctAnalysis") }}
              </div>
            </div>
            <div
              class="info-box from-orange-50 to-orange-100 border-orange-200"
            >
              <div class="info-box-title text-orange-600">
                {{ results.timeUsed }}{{ t("criticalThinkingTest.seconds") }}
              </div>
              <div class="info-box-body">
                {{ t("criticalThinkingTest.timeUsed") }}
              </div>
            </div>
          </div>
          <Button
            @click="handleComplete"
            class="w-full bg-gradient-to-r from-yellow-600 to-orange-500 hover:from-yellow-700 hover:to-orange-600 text-white py-3 text-lg font-semibold shadow-lg"
            size="lg"
          >
            {{ t("criticalThinkingTest.viewDetailedResultsButton") }}
          </Button>
        </CardContent>
      </Card>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, onUnmounted } from "vue";
import {
  Lightbulb,
  Clock,
  Trophy,
  Star,
  AlertTriangle,
  X,
} from "lucide-vue-next";
import { CRITICAL_THINKING_POOL } from "../constants/criticalThinking";
const { t } = useI18n();
const emit = defineEmits(["complete"]);

// --- Constants ---
const QUESTIONS_PER_TEST = 12;
const TYPE_DISPLAY_NAMES = {
  assumption: t("criticalThinkingTest.assumption"),
  argument_evaluation: t("criticalThinkingTest.argument_evaluation"),
  logical_fallacy: t("criticalThinkingTest.logical_fallacy"),
  cause_effect: t("criticalThinkingTest.cause_effect"),
  inference: t("criticalThinkingTest.inference"),
  bias_detection: t("criticalThinkingTest.bias_detection"),
};

// --- State ---
const stage = ref("instructions");
const currentQuestion = ref(0);
const selectedQuestions = ref([]);
const responses = ref([]);
const timeLeft = ref(900);
const startTime = ref(0);
const score = ref(0);
const showFeedback = ref(false);
const feedbackCorrect = ref(false);
const feedbackExplanation = ref("");

let timer = null;

// --- Computed Properties ---
const currentQuestionData = computed(
  () => selectedQuestions.value[currentQuestion.value]
);
const typeName = computed(
  () => TYPE_DISPLAY_NAMES[currentQuestionData.value?.type] || ""
);
const typeClass = computed(() => {
  if (!currentQuestionData.value) return "";
  switch (currentQuestionData.value.type) {
    case "assumption":
      return "bg-blue-100 text-blue-700 border-blue-300";
    case "argument_evaluation":
      return "bg-green-100 text-green-700 border-green-300";
    case "logical_fallacy":
      return "bg-red-100 text-red-700 border-red-300";
    case "cause_effect":
      return "bg-purple-100 text-purple-700 border-purple-300";
    case "inference":
      return "bg-indigo-100 text-indigo-700 border-indigo-300";
    default:
      return "bg-orange-100 text-orange-700 border-orange-300";
  }
});
const difficultyText = computed(() => {
  if (!currentQuestionData.value) return "";
  switch (currentQuestionData.value.difficulty) {
    case "easy":
      return t("criticalThinkingTest.easy");
    case "medium":
      return t("criticalThinkingTest.medium");
    case "hard":
      return t("criticalThinkingTest.hard");
    default:
      return "";
  }
});
const difficultyClass = computed(() => {
  if (!currentQuestionData.value) return "";
  switch (currentQuestionData.value.difficulty) {
    case "easy":
      return "bg-green-100 text-green-700 border-green-300";
    case "medium":
      return "bg-yellow-100 text-yellow-700 border-yellow-300";
    case "hard":
      return "bg-red-100 text-red-700 border-red-300";
    default:
      return "";
  }
});
const results = computed(() => {
  const totalQuestions = selectedQuestions.value.length;
  if (totalQuestions === 0) return { accuracy: 0, timeUsed: 0 };
  const accuracy = Math.round((score.value / totalQuestions) * 100);
  const timeUsed = Math.round((Date.now() - startTime.value) / 1000);
  return { accuracy, timeUsed };
});

// --- Methods ---
const selectRandomQuestions = () => {
  const shuffled = [...CRITICAL_THINKING_POOL].sort(() => 0.5 - Math.random());
  const questionsByType = {
    assumption: [],
    argument_evaluation: [],
    logical_fallacy: [],
    cause_effect: [],
    inference: [],
    bias_detection: [],
  };
  shuffled.forEach((q) => {
    if (questionsByType[q.type] && questionsByType[q.type].length < 2) {
      questionsByType[q.type].push(q);
    }
  });
  const selected = Object.values(questionsByType).flat();
  if (selected.length < QUESTIONS_PER_TEST) {
    const remaining = shuffled.filter(
      (q) => !selected.some((s) => s.id === q.id)
    );
    selected.push(...remaining.slice(0, QUESTIONS_PER_TEST - selected.length));
  }
  return selected.sort(() => 0.5 - Math.random()).slice(0, QUESTIONS_PER_TEST);
};

const handleStartTest = () => {
  selectedQuestions.value = selectRandomQuestions();
  stage.value = "test";
  startTime.value = Date.now();
};

const handleAnswer = (answerIndex) => {
  const question = currentQuestionData.value;
  const correct = answerIndex === question.correct;
  responses.value.push(answerIndex);
  if (correct) {
    score.value++;
  }
  feedbackCorrect.value = correct;
  feedbackExplanation.value = question.explanation;
  showFeedback.value = true;
};

const handleCloseFeedback = () => {
  showFeedback.value = false;
  if (currentQuestion.value < selectedQuestions.value.length - 1) {
    currentQuestion.value++;
  } else {
    stage.value = "results";
  }
};

const handleComplete = () => {
  const totalQuestions = selectedQuestions.value.length;
  const typeStats = {};
  selectedQuestions.value.forEach((question, index) => {
    const type = question.type;
    if (!typeStats[type]) typeStats[type] = { correct: 0, total: 0 };
    typeStats[type].total++;
    if (responses.value[index] === question.correct) typeStats[type].correct++;
  });

  emit("complete", {
    id: Date.now().toString(),
    testType: "critical-thinking",
    score: results.value.accuracy,
    completedAt: new Date(),
    duration: results.value.timeUsed,
    details: {
      totalQuestions,
      correctAnswers: score.value,
      accuracy: results.value.accuracy,
      averageTimePerQuestion: Math.round(
        results.value.timeUsed / totalQuestions
      ),
      typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
        type: TYPE_DISPLAY_NAMES[type] || type,
        accuracy:
          stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
        correct: stats.correct,
        total: stats.total,
      })),
    },
  });
};

// --- Lifecycle Hooks ---
watch(stage, (newStage) => {
  if (newStage === "test" && !timer) {
    timer = setInterval(() => {
      if (timeLeft.value <= 1) {
        stage.value = "results";
        clearInterval(timer);
      } else {
        timeLeft.value--;
      }
    }, 1000);
  } else if (newStage !== "test" && timer) {
    clearInterval(timer);
    timer = null;
  }
});

onUnmounted(() => {
  if (timer) clearInterval(timer);
});
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease-out;
}
.slide-down-enter-from,
.slide-down-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}
.step-number {
  @apply w-6 h-6 bg-yellow-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5;
}
.task-preview-box {
  @apply bg-gradient-to-br rounded-xl p-4 border;
}
.info-box {
  @apply text-center p-4 bg-gradient-to-br rounded-xl border;
}
.info-box-title {
  @apply text-2xl font-bold mb-1;
}
.info-box-body {
  @apply text-sm;
}
.result-row {
  @apply flex justify-between items-center p-3 bg-slate-50 rounded-lg;
}
btn:hover {
  background: #000;
}
</style>
